import React from 'react';
import {connect} from 'dva/index';
import {Button, Checkbox, Col, Form, Input, InputNumber, message, Radio, Row, Table, Tabs} from 'antd';
import SingleDragger from "../common/SingleDragger";
import {download} from '../../utils/commons';
import Constants from '../../utils/Constants';

const dateFormat = 'YYYY-MM-DD';
const FormItem = Form.Item;
const TabPane = Tabs.TabPane;
const CheckboxGroup = Checkbox.Group;
const RadioGroup = Radio.Group;
const R = require("ramda");

const orderDeclareInfo = Form.create()(class OrderDeclareInfo extends React.Component {
    constructor(props) {
        super(props);
        let normalDeclareList = this.props.order.odDeclare && this.props.order.odDeclare.normalDeclareList ? this.props.order.odDeclare.normalDeclareList : [];
        normalDeclareList.map(item => item.id = this.count++);
        let payDeclareList= this.props.order.odDeclare && this.props.order.odDeclare.payDeclareList ? this.props.order.odDeclare.payDeclareList : [];
        payDeclareList.map(item => item.id = this.payCount++);
        this.state = {
            normalDeclareList,
            defaultNormalDeclareList: R.clone(normalDeclareList),
            payDeclareList,
            defaultPayDeclareList: R.clone(payDeclareList)
        };
    }

    count = 1;
    payCount = 1;
    componentWillReceiveProps(nextProps) {
        let dataSource = this.props.order.odDeclare ? this.props.order.odDeclare : {};
        let nextDataSource = nextProps.order.odDeclare ? nextProps.order.odDeclare : {};
        if (!R.equals(dataSource.normalDeclareList)(nextDataSource.normalDeclareList)) {
            let normalDeclareList = nextDataSource.normalDeclareList ? nextDataSource.normalDeclareList : [];
            normalDeclareList.map(item => item.id = this.count++);
            this.setState({ normalDeclareList, defaultNormalDeclareList: R.clone(normalDeclareList) });
        }
        if (!R.equals(dataSource.payDeclareList)(nextDataSource.payDeclareList)) {
            let payDeclareList = nextDataSource.payDeclareList ? nextDataSource.payDeclareList : [];
            payDeclareList.map(item => item.id = this.payCount++);
            this.setState({ payDeclareList, defaultPayDeclareList: R.clone(payDeclareList) });
        }
    }

    handleReset = () => {
        this.setState({ 
            normalDeclareList: this.state.defaultNormalDeclareList,
            payDeclareList: this.state.defaultPayDeclareList
        });
    }

    handleExportDeclarePlan = () => {        //导出报关计划
        let id = R.isNil(this.props.order.odDeclare.id) ? "" : this.props.order.odDeclare.id;
        let url = apiPath.mc + "/api/file/export/declarePlan/" + id;
        let conditions = null;
        download(url, conditions);
    }

    cleanItem = () =>{
        this.props.form.setFieldsValue({ attachedreceiptno: undefined })
    }

    form = {};
    flag = true;
    handleCollectForm = () => {
        this.props.form.validateFields({ force: true }, (errors, values) => {
            if (errors) {
                this.flag = false;
                return;
            } else {
                this.flag = true;
                this.form = { ...values };
                let data = this.props.order.odDeclare ? this.props.order.odDeclare : {};
                let orderId = data ? data.orderId : null;
                let normalDeclareList = R.clone(this.state.normalDeclareList ? this.state.normalDeclareList : []);
                let payDeclareList = R.clone(this.state.payDeclareList ? this.state.payDeclareList : []);
                normalDeclareList.map(item => {
                    if (!item.company || !item.weight || !item.count) this.flag = false;
                    else item.id = undefined
                });
                payDeclareList.map(item => {
                    if (!item.weight || !item.count) this.flag = false;
                    else item.id = undefined
                });
                if (!this.flag) message.error("正常单报关或买单报关信息不完整！");
                this.form.normalDeclareList = normalDeclareList;
                this.form.payDeclareList = payDeclareList;
                this.form.orderId = orderId;
            }
        })
        return this.flag;
    }

    refreshInput = (id, prop, e) => {
        this.refreshInputNumber(id, prop, 'normal', e.target.value);
    }

    refreshInputNumber = (id, prop, type, e) => {
        let normalDeclareList = this.state.normalDeclareList;
        let payDeclareList = this.state.payDeclareList;
        if(type == 'normal'){
            normalDeclareList.map(item => { if (item.id === id) item[prop] = e });
        }
        if(type == 'pay'){
            payDeclareList.map(item => { if (item.id === id) item[prop] = e });
        }
        this.setState(normalDeclareList, payDeclareList);
    }

    onDelete = (id, type) => {
        let normalDeclareList = this.state.normalDeclareList;
        let payDeclareList = this.state.payDeclareList;
        if(type == "normal"){
            normalDeclareList.splice(normalDeclareList.findIndex(item => item.id === id), 1);
        }
        if(type == "pay"){
            payDeclareList.splice(payDeclareList.findIndex(item => item.id === id), 1);
        }
        this.setState({normalDeclareList, payDeclareList});
    }

    onAdd = (type) => {
        let normalDeclareList = this.state.normalDeclareList;
        let payDeclareList = this.state.payDeclareList;
        if(type == "normal"){
            normalDeclareList.push({ id: this.count++ });
        }
        if(type == "pay"){
            payDeclareList.push({ id: this.payCount++ });
        }
        this.setState({normalDeclareList, payDeclareList});
    }

    getNormalColumns = (disabled) => {
        let normalColumns = [
            {
                title: '经营单位', dataIndex: 'company', key: 'company', width: disabled ? '50%' : '40%', render: (text, record, index) => {
                    if (disabled) return <span>{record.company}</span>
                    else return <Input maxLength="50" value={record.company} style={{ width: '100%' }} onChange={this.refreshInput.bind(this, record.id, 'company')} />
                }
            },
            {
                title: '重量(KGS)', dataIndex: 'weight', key: 'weight', width: '25%', render: (text, record, index) => {
                    if (disabled) return <span>{record.weight}</span>
                    else return <InputNumber maxLength="18" value={record.weight} style={{ width: '100%' }} onChange={this.refreshInputNumber.bind(this, record.id, 'weight', 'normal')} />
                }
            },
            {
                title: '件数', dataIndex: 'count', key: 'count', width: '25%', render: (text, record, index) => {
                    if (disabled) return <span>{record.count}</span>
                    else return <InputNumber maxLength="11" value={record.count} style={{ width: '100%' }} onChange={this.refreshInputNumber.bind(this, record.id, 'count', 'normal')} />
                }
            }
        ];
        if (!disabled) normalColumns.push({
            key: 'delete', width: '10%', render: (text, record, index) => {
                return <Button type="primary" icon="delete" style={{ marginRight: 5 }} size={'small'} onClick={this.onDelete.bind(this, record.id, "normal")} />
            }
        })
        return normalColumns;
    }

    getPayColumns = (disabled) => {
        let payColumns = [
            {
                title: '重量(KGS)', dataIndex: 'weight', key: 'weight', width: '45%', render: (text, record, index) => {
                    if (disabled) return <span>{record.weight}</span>
                    else return <InputNumber maxLength="18" value={record.weight} style={{ width: '96%' }} onChange={this.refreshInputNumber.bind(this, record.id, 'weight', 'pay')} />
                }
            },
            {
                title: '件数', dataIndex: 'count', key: 'count', width: '45%', render: (text, record, index) => {
                    if (disabled) return <span>{record.count}</span>
                    else return <InputNumber maxLength="11" value={record.count} style={{ width: '100%' }} onChange={this.refreshInputNumber.bind(this, record.id, 'count', 'pay')} />
                }
            }
        ];
        if (!disabled) payColumns.push({
            key: 'delete', width: '10%', render: (text, record, index) => {
                return <Button type="primary" icon="delete" style={{ marginRight: 5 }} size={'small'} onClick={this.onDelete.bind(this, record.id, "pay")} />
            }
        })
        return payColumns;
    }

    checkOrderDeclareInfo = () => {
        if (this.handleCollectForm()) {
            return this.form;
        }
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        let dataSource = this.props.order.odDeclare ? this.props.order.odDeclare : {};
        let order = this.props.order.order ? this.props.order.order : {};

        let formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 14 } };
        let declareBillUrl = dataSource.declareBillUrl ? dataSource.declareBillUrl : undefined;
        let passNoticeUrl = dataSource.passNoticeUrl ? dataSource.passNoticeUrl : undefined;
        let otherUrl = dataSource.otherUrl ? dataSource.otherUrl : undefined;

        const divWithOutBorderBottom = {
            display: 'flex',
            borderRight: '1px solid #e9e9e9',
            borderLeft: '1px solid #e9e9e9',
            borderTop: '1px solid #e9e9e9',
            borderSpacing: 0,
            lineHeight: 4.2,
            textAlign: 'left',
        }

        return (
            <div>
                <Form>
                    <Tabs tabPosition={'top'}>
                        <TabPane tab="制定报关计划" key="1">
                            <div style={{ width: '88%', marginLeft: 50 }}>
                                <div style={{ textAlign: 'center' }}>
                                    <div><span><b><font size="4">广州瀚森乐达供应链管理有限公司——报关计划</font></b></span></div>
                                    <div style={{ marginTop: 10 }}><span><font size="2">地址: 广州市海珠区后滘镇后滘西大街139号鲁思湖畔空间创意园B1-207室</font></span>
                                        <span style={{ marginLeft: 50 }}>TEL: 020-87512605-813</span>
                                    </div>
                                </div>
                                <div style={{ textAlign: 'left', marginTop: 10, marginBottom: 10 }}>
                                    <div><span>TO: {dataSource.declareSupplierName}</span></div>
                                    <div style={{ marginTop: 10 }}><span>FM: {dataSource.gdUser} / {dataSource.gdTelephone}</span></div>
                                    {/* <div style={{ marginTop: 10 }}><span>SO号: {dataSource.soNo}</span></div> */}
                                    <div style={{ marginTop: 10 }}><span>柜型/柜量: {dataSource.size20gp}*20GP   {dataSource.weight20gp}KGS &nbsp;&nbsp;&nbsp; {dataSource.size40gp}*40GP   {dataSource.weight40gp}KGS &nbsp;&nbsp;&nbsp; {dataSource.size40hq}*40HQ   {dataSource.weight40hq}KGS</span></div>
                                </div>
                                <div style={divWithOutBorderBottom}>
                                    <div style={{ width: '100%', marginLeft: 10, borderRight: '1px solid #e9e9e9' }}>
                                        <div>SO号 &nbsp;&nbsp;
                                            <span>
                                                {getFieldDecorator('soNo', {
                                                    initialValue: dataSource.soNo
                                                })(
                                                    <Input maxLength="300" disabled={dataSource.status == "2" || dataSource.status == "3" ? true : this.props.disabled} style={{ width: '90%', marginBottom: 5, marginLeft: 24 }} />
                                                    )}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div style={divWithOutBorderBottom}>
                                    <div style={{ width: '100%', marginLeft: 10, borderRight: '1px solid #e9e9e9' }}>
                                        <div>柜号 &nbsp;&nbsp;
                                            <span>
                                                {getFieldDecorator('cntrNo', {
                                                    initialValue: order.cntrNo
                                                })(
                                                    <Input maxLength="300" disabled={dataSource.status == "2" || dataSource.status == "3" ? true : this.props.disabled} style={{ width: '90%', marginBottom: 5, marginLeft: 24 }} />
                                                    )}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div style={divWithOutBorderBottom}>
                                    <div style={{ width: '100%', marginLeft: 10, borderRight: '1px solid #e9e9e9' }}>
                                        <div>封条号 &nbsp;&nbsp;
                                            <span>
                                                {getFieldDecorator('sealNumber', {
                                                    initialValue: order.sealNumber
                                                })(
                                                    <Input maxLength="50" disabled={dataSource.status == "2" || dataSource.status == "3" ? true : this.props.disabled} style={{ width: '90%', marginBottom: 5, marginLeft: 13 }} />
                                                    )}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div style={divWithOutBorderBottom}>
                                    <div style={{ width: '100%', marginLeft: 10, borderRight: '1px solid #e9e9e9' }}>
                                        <div>出口码头 &nbsp;&nbsp;
                                            <span>
                                                {getFieldDecorator('exportWharf', {
                                                    initialValue: dataSource.exportWharf
                                                })(
                                                    <Input maxLength="300" disabled={dataSource.status == "2" || dataSource.status == "3" ? true : this.props.disabled} style={{ width: '90%', marginBottom: 5 }} />
                                                    )}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div style={divWithOutBorderBottom}>
                                    <div style={{ width: '100%', marginLeft: 10, borderRight: '1px solid #e9e9e9' }}>
                                        <div>报关要求 &nbsp;&nbsp;
                                            <span>
                                                {getFieldDecorator('declareRequire', {
                                                    initialValue: dataSource.declareRequire
                                                })(
                                                    <Input maxLength="300" disabled={dataSource.status == "2" || dataSource.status == "3" ? true : this.props.disabled} style={{ width: '90%', marginBottom: 5 }} />
                                                    )}
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div style={divWithOutBorderBottom}>
                                    <div style={{ width: '90%', marginLeft: 10 }}>
                                        <div>报关方式 &nbsp;&nbsp;
                                            <span>
                                                {getFieldDecorator('declareType', {
                                                    initialValue: dataSource.declareType
                                                })(
                                                    // <Select style={{ width: '60%', marginBottom: 5 }}  disabled={dataSource.status == "2" || dataSource.status == "3" ? true : this.props.disabled}>
                                                    //     <Select.Option value="1">国际中转</Select.Option>
                                                    //     <Select.Option value="2">内河转关</Select.Option>
                                                    //     <Select.Option value="3">一关通</Select.Option>
                                                    // </Select>
                                                    //<Input maxLength="50" disabled={dataSource.status == "2" || dataSource.status == "3" ? true : this.props.disabled} style={{ width: '90%', marginBottom: 5 }} />
                                                    <RadioGroup style={{ width: '60%' }}  disabled={dataSource.status == "2" || dataSource.status == "3" ? true : this.props.disabled}>
                                                        <Radio value="1">国际中转</Radio>
                                                        <Radio value="2">内河转关</Radio>
                                                        <Radio value="3">一关通</Radio>
                                                    </RadioGroup>
                                                    )}
                                            </span>
                                        </div>
                                    </div>
                                    <div style={{ width: '10%', marginLeft: 10 }}>
                                        <Button type="primary" icon="delete" size={'small'} onClick={this.cleanItem.bind(this)}>重置</Button>
                                    </div>
                                </div>
                                <div style={divWithOutBorderBottom}>
                                    <div style={{ width: '8%', marginLeft: 10, borderRight: '1px solid #e9e9e9' }}>提单 </div>
                                    <div style={{ width: '46%', marginLeft: 10, borderRight: '1px solid #e9e9e9' }}>
                                        <div>总毛重 &nbsp;&nbsp; <span>
                                            {getFieldDecorator('totalWeight', {
                                                initialValue: dataSource.totalWeight
                                            })(
                                                <InputNumber maxLength="18" disabled={dataSource.status == "2" || dataSource.status == "3" ? true : this.props.disabled} style={{ width: '75%', marginBottom: 5 }} />
                                                )}KGS
                                        </span>
                                        </div>
                                    </div>
                                    <div style={{ width: '46%', marginLeft: 10, borderRight: '1px solid #e9e9e9' }}>
                                        <div>总件数 &nbsp;&nbsp; <span>
                                            {getFieldDecorator('totalNum', {
                                                initialValue: dataSource.totalNum
                                            })(
                                                <InputNumber maxLength="18" disabled={dataSource.status == "2" || dataSource.status == "3" ? true : this.props.disabled} style={{ width: '80%', marginBottom: 5 }} />
                                                )}
                                        </span>
                                        </div>
                                    </div>
                                </div>
                                <div style={divWithOutBorderBottom}>
                                    <div style={{ width: '20%', textAlign: 'center', borderRight: '1px solid #e9e9e9' }}>{(dataSource.status == "2" || dataSource.status == "3" ? true : this.props.disabled) ? <span>{"正常单报关(" + this.state.normalDeclareList.length + ")"}</span> : <Button type="primary" icon="plus" size={'small'} onClick={this.onAdd.bind(this, "normal")}>{"正常单报关(" + this.state.normalDeclareList.length + ")"}</Button>}</div>
                                    <div style={{ width: '100%', display: dataSource.normalDeclareList && this.state.normalDeclareList.length > 0 ? 'inline-block' : 'none' }}>
                                        <Table bordered={false} className="customTableSmall" loading={this.props.loading} rowKey='id' dataSource={this.state.normalDeclareList} columns={this.getNormalColumns(dataSource.status == "2" || dataSource.status == "3" ? true : this.props.disabled)} bordered={false} size={'small'} pagination={false} />
                                    </div>
                                </div>
                                <div style={divWithOutBorderBottom}>
                                    <div style={{ width: '20%', textAlign: 'center', borderRight: '1px solid #e9e9e9' }}>{(dataSource.status == "2" || dataSource.status == "3" ? true : this.props.disabled) ? <span>{"买单报关(" + this.state.payDeclareList.length + ")"}</span> : <Button type="primary" icon="plus" size={'small'} onClick={this.onAdd.bind(this, "pay")}>{"买单报关(" + this.state.payDeclareList.length + ")"}</Button>}</div>
                                    <div style={{ width: '100%', display: dataSource.payDeclareList && this.state.payDeclareList.length > 0 ? 'inline-block' : 'none' }}>
                                        <Table bordered={false} className="customTableSmall" loading={this.props.loading} rowKey='id' dataSource={this.state.payDeclareList} columns={this.getPayColumns(dataSource.status == "2" || dataSource.status == "3" ? true : this.props.disabled)} bordered={false} size={'small'} pagination={false} />
                                    </div>
                                </div>
                                {/* <div style={divWithOutBorderBottom}>
                                    <div style={{ width: '10%', marginLeft: 10, borderRight: '1px solid #e9e9e9' }}>买单报关 </div>
                                    <div style={{ width: '30%', marginLeft: 10, borderRight: '1px solid #e9e9e9' }}>
                                        <div>票数 &nbsp; <span>
                                            {getFieldDecorator('payBillPoll', {
                                                initialValue: dataSource.payBillPoll
                                            })(
                                                <InputNumber maxLength="11" disabled={dataSource.status == "2" || dataSource.status == "3" ? true : this.props.disabled} style={{ width: '80%', marginBottom: 5 }} />
                                                )}
                                        </span>
                                        </div>
                                    </div>
                                    <div style={{ width: '30%', marginLeft: 10, borderRight: '1px solid #e9e9e9' }}>
                                        <div>重量 &nbsp; <span>
                                            {getFieldDecorator('payBillWeight', {
                                                initialValue: dataSource.payBillWeight
                                            })(
                                                <InputNumber maxLength="18" disabled={dataSource.status == "2" || dataSource.status == "3" ? true : this.props.disabled} style={{ width: '80%', marginBottom: 5 }} />
                                                )}KGS
                                        </span>
                                        </div>
                                    </div>
                                    <div style={{ width: '30%', marginLeft: 10, borderRight: '1px solid #e9e9e9' }}>
                                        <div>件数 &nbsp;&nbsp; <span>
                                            {getFieldDecorator('payBillPackagesNum', {
                                                initialValue: dataSource.payBillPackagesNum
                                            })(
                                                <InputNumber maxLength="11" disabled={dataSource.status == "2" || dataSource.status == "3" ? true : this.props.disabled} style={{ width: '78%', marginBottom: 5 }} />
                                                )}
                                        </span>
                                        </div>
                                    </div>
                                </div> */}
                                <div style={divWithOutBorderBottom}>
                                    <div style={{ marginLeft: 248 }}><font size="2">注意: 正常单报关件数+买单报关件数=提单总件数<br />
                                        <div style={{ marginLeft: 30 }}>正常单报关重量+买单报关重量=提单总毛重</div></font></div>
                                </div>
                                <div style={Object.assign({}, { borderBottom: '1px solid #e9e9e9', marginBottom: 20 }, divWithOutBorderBottom)}>
                                    <div style={{ width: '50%', marginLeft: 10, borderRight: '1px solid #e9e9e9' }}>
                                        <div>正常单报关费 &nbsp; <span>
                                            {getFieldDecorator('normalDeclareFee', {
                                                initialValue: dataSource.normalDeclareFee
                                            })(
                                                <Input maxLength="11" disabled={dataSource.status == "2" || dataSource.status == "3" ? true : this.props.disabled} style={{ width: '76%', marginBottom: 5 }} />
                                                )}
                                        </span>
                                        </div>
                                    </div>
                                    <div style={{ width: '50%', marginLeft: 10, borderRight: '1px solid #e9e9e9' }}>
                                        <div>买单报关费 &nbsp; <span>
                                            {getFieldDecorator('payBillDeclareFee', {
                                                initialValue: dataSource.payBillDeclareFee
                                            })(
                                                <Input maxLength="11" disabled={dataSource.status == "2" || dataSource.status == "3" ? true : this.props.disabled} style={{ width: '78%', marginBottom: 5 }} />
                                                )}
                                        </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </TabPane>
                    </Tabs>

                    {dataSource.status == "2" || dataSource.status == "3" ?
                        <Tabs tabPosition={'top'}>
                            <TabPane tab="报关凭证" key="1">
                                <Row>
                                    <Col span={4} style={{ marginLeft: 90, marginTop: 10, marginBottom: 10 }}>
                                        <a href="#" onClick={this.handleExportDeclarePlan.bind(this)}>导出报关计划</a>
                                    </Col>
                                </Row>
                                <Row>
                                    <Col span={12}>
                                        <FormItem {...formItemLayout} label={<span className="ant-form-item-required">报关底单</span>} hasFeedback>
                                            <SingleDragger url={declareBillUrl} ref="declareBillUrl" dataSource={dataSource} module={Constants.ORDERDEC_MODULES[0]} disabled={dataSource.status == "3" ? true : this.props.disabled} />
                                        </FormItem>
                                    </Col>
                                    <Col span={12}>
                                        <FormItem {...formItemLayout} label={<span className="ant-form-item-required">放行通知书</span>} hasFeedback>
                                            <SingleDragger url={passNoticeUrl} ref="passNoticeUrl" dataSource={dataSource} module={Constants.ORDERDEC_MODULES[1]} disabled={dataSource.status == "3" ? true : this.props.disabled} />
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row>
                                    <Col span={12}>
                                        <FormItem {...formItemLayout} label={<span className="ant-form-item-required">其他资料</span>} hasFeedback>
                                            <SingleDragger url={otherUrl} ref="otherUrl" dataSource={dataSource} module={Constants.ORDERDEC_MODULES[2]} disabled={dataSource.status == "3" ? true : this.props.disabled} />
                                        </FormItem>
                                    </Col>
                                </Row>
                            </TabPane>
                        </Tabs>
                        : ""}
                </Form>
            </div>
        )
    }
})

function mapStateToProps(state) {
    return {
        loading: state.loading.models.order, order: state.order
    };
}

export default connect(mapStateToProps)(orderDeclareInfo);